package com.wva.censor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationPlusRequest;
import com.aliyun.green20220302.models.TextModerationPlusResponse;
import com.aliyun.green20220302.models.TextModerationPlusResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.wva.censor.properties.AliyunGreenProperties;
import com.wva.censor.service.TextCensorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 阿里云文本审核增强版
 * @Author: hong
 * @Date: 2025/2/15 20:17:45
 */
@Service
@Slf4j
public class AliyunTextModerationPlus implements TextCensorService {
    private static Client client;

    @Autowired
    AliyunGreenProperties aliyunGreenProperties;

    @Override
    public Boolean censor(String text) throws Exception {
        if (client == null) {
            Config config = new Config();
            config.setAccessKeyId(aliyunGreenProperties.getAccessId());
            config.setAccessKeySecret(aliyunGreenProperties.getAccessSecret());
            //接入区域和地址请根据实际情况修改
            config.setRegionId("cn-shanghai");
            config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
            //读取时超时时间，单位毫秒（ms）。
            config.setReadTimeout(6000);
            //连接时超时时间，单位毫秒（ms）。
            config.setConnectTimeout(3000);
            client = new Client(config);
        }

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", text);

        TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
        // 检测类型
        textModerationPlusRequest.setService("llm_query_moderation");
        textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationPlusResponse response = client.textModerationPlus(textModerationPlusRequest);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                Integer code = result.getCode();
                if (200 == code) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    return StrUtil.equals("none", data.riskLevel);
                } else {
                    log.error("阿里云内容安全服务检测出错: code={}", code);
                    return null;
                }
            } else {
                log.error("阿里云服务出现问题，响应错误码={}", response.getStatusCode());
                return null;
            }
        } catch (Exception e) {
            log.error("无法连接到阿里云内容安全");
            return null;
        }
    }
}
